package vpc

import (
    "bytes"
    "encoding/json"
    "fcs-api/src/app/model"
    "fcs-api/src/app/utils"

    "git.inspur.com/x/common/loggerfactory"
)

const BindUri = "vpc/v1/enis/action/bind-ifcs"
const UnBindUri = "vpc/v1/enis/action/unbind-ifcs"

var logger = loggerfactory.GetLogger()

type PortInfo struct {
    VpcId    string `json:"vpcId"`
    ServerId string `json:"serverId"`
    SubnetId string `json:"subnetId"`
    PortId   string `json:"portId,omitempty"`
}

func AddPortBinding(vpcId, subnetId, serverId, token string) (*model.PortBinding, error) {
    url := model.Base.VpcHost + BindUri
    b, _ := json.Marshal(PortInfo{
        VpcId:    vpcId,
        ServerId: serverId,
        SubnetId: subnetId,
    })
    logger.Debug("AddPortBinding: url is %s, body is %s", url, string(b))
    body, err := utils.HttpReq(url, token, "POST", bytes.NewReader(b), nil)
    if err != nil {
        return nil, err
    }
    portBinding := new(model.PortBinding)
    err = json.Unmarshal(body, portBinding)
    if err != nil {
        _ = logger.Error("AddPortBinding: Unmarshal bind-ifcs result error, %s", err.Error())
        return nil, err
    }
    logger.Debug("AddPortBinding: body is %s", string(body))
    logger.Debug("AddPortBinding: portBinding is %s", portBinding)
    return portBinding, nil
}

func RemovePortBinding(vpcId, subnetId, serverId, portId, token string) error {
    url := model.Base.VpcHost + UnBindUri
    b, _ := json.Marshal(PortInfo{
        VpcId:    vpcId,
        ServerId: serverId,
        SubnetId: subnetId,
        PortId:   portId,
    })
    logger.Debug("RemovePortBinding: url is %s, body is %s", url, string(b))
    _, err := utils.HttpReq(url, token, "POST", bytes.NewReader(b), nil)
    if err != nil {
        return err
    }
    return nil
}
